/***********************************************
*	名称:数据导出
*	说明:数据导出成excel,并支持传到七牛
*	作者:钱纯净
************************************************/
package excel

import (
	"os"
	"strconv"
	"time"

	"gitee.com/wzqj/frame/tools/qinius"
	"github.com/360EntSecGroup-Skylar/excelize"
)

const (
	defFilePath  = "./export/"
	defSheetName = "Sheet1"
	defSuffix    = ".xlsx"
)

//导出数据

type Export struct {
	data     map[string][][]interface{} //数据源
	filePath string                     //文件夹路径,可选
	fileName string                     //文件名称,可选
	err      string                     //错误信息

	qiniu *qinius.Qiniu //七牛
}

//新建导出
//
func NewExport(filePath ...string) *Export {
	data := &Export{
		data:     make(map[string][][]interface{}),
		filePath: defFilePath,
		fileName: strconv.Itoa(int(time.Now().UnixNano())) + defSuffix,
		qiniu:    qinius.DefQiniu(),
	}
	if len(filePath) != 0 {
		data.fileName = filePath[0]
	}
	return data
}

//添加数据
//@data,数据源
//@sheetName,分页名称,可选(默认sheet1)
func (this *Export) SetData(data [][]interface{}, sheetName ...string) *Export {
	name := defSheetName
	if len(sheetName) != 0 && len(sheetName[0]) != 0 {
		name = sheetName[0]
	}
	this.data[name] = data
	return this
}

//设置文件路径
func (this *Export) SetFilePath(filePath string) *Export {
	this.filePath = filePath
	return this
}

//设置文件名称
func (this *Export) SetFileName(fileName string) *Export {
	this.fileName = fileName
	return this
}

//设置七牛
func (this *Export) SetQiniu(qiniu *qinius.Qiniu) *Export {
	if qiniu != nil {
		this.qiniu = qiniu
	}
	return this
}

//保存本地
func (this *Export) Save(fileName ...string) (string, error) {
	if len(fileName) != 0 {
		this.SetFileName(fileName[0])
	}
	err := os.MkdirAll(this.filePath, 0766)
	if err != nil {
		return null, err
	}
	if len(this.err) != 0 {
		return null, this
	}
	return this.toExcel()
}

//上传到七牛云
func (this *Export) Upload(fileName ...string) (string, error) {
	_, err := this.Save(fileName...)
	return this.qiniu.SetErr(err).Upload(this.filePath, this.fileName)
}

//生成excel文件,并保存到本地
func (this *Export) toExcel() (string, error) {
	f := excelize.NewFile()
	for name, sheet := range this.data {
		index := f.NewSheet(name)
		f.SetActiveSheet(index)
		for i, row := range sheet {
			for k, v := range row {
				f.SetCellValue(name, ToString(k+1, i+1), v)
			}
		}
	}
	return this.filePath + this.fileName, f.SaveAs(this.filePath + this.fileName)
}

func (this Export) Error() string {
	return this.err
}
